import urllib2
import json
import json_org_examples as examples
import json_org_suit as suit


def req(_s, resp_handler):
    request = urllib2.Request('http://127.0.0.1:60000')
    request.data = _s
    resp = urllib2.urlopen(request)
    resp_str = resp.read()
    resp_json = json.loads(resp_str)
    resp_handler(resp_json['status'], resp_json['message'])


def build_example_handler(c):
    def lam(status, message):
        if status != 'success':
            raise AssertionError('Failed! ' + str(c) + ' with message ' + str(message))
        if c != message:
            raise AssertionError('Failed! expecting ' + str(c) + ', but got ' + str(message))

    return lam


# examples:
for case in examples.CASES:
    print ('test case:' + str(case))
    s = json.dumps(case)
    req(s, build_example_handler(case))


# suit:
# fail:
def build_fail_handler(_s):
    def lam(status, _):
        if status != 'error':
            raise AssertionError('Failed! ' + _s + ' should fail!')

    return lam


for i in xrange(suit.FAIL_MAX):
    if i + 1 in suit.SKIP_FAIL:
        continue
    print ('test fail' + str(i + 1))
    f = open('cases/fail' + str(i + 1) + '.json', 'r')
    s = f.read()
    f.close()
    req(s, build_fail_handler(s))


# pass
def build_pass_handler(_s):
    def lam(status, message):
        if status != 'success':
            raise AssertionError('Failed! ' + _s + ' should pass, but failed with message ' + str(message))
        json_s = json.loads(_s)
        if json_s != message:
            raise AssertionError('Failed! expecting ' + str(json_s) + ', but got ' + str(message))

    return lam


for i in xrange(suit.PASS_MAX):
    print ('test pass' + str(i + 1))
    f = open('cases/pass' + str(i + 1) + '.json', 'r')
    s = f.read()
    f.close()
    req(s, build_pass_handler(s))
